class PositionsController < ApplicationController
  def create
    @position = Position.new
    render :action => "edit"
  end

  def edit
    @position = Position.find(params[:id])
  end

  def save
    if params[:id].nil?
      @position = Position.new
    else
      @position = Position.find(params[:id])
    end

    if params[:commit] == "Save"

      names = params[:member][:full_name].split(' ')

      #If member has a middle name, put it in the proper field.
      #If member has multiple middle names, we're screwed!
      if names.size == 3
        unless Member.find_by_first_name_and_last_name(names[0], names[1] + " " + names[2]).nil?
          @member = Member.find_by_first_name_and_last_name(names[0], names[1] + " " + names[2])
        else
          @member = Member.find_by_first_name_and_last_name(names[0] + " " + names[1], names[2])
        end
      else
        @member = Member.find_by_first_name_and_last_name(names[0], names[1])
      end

      unless @member.nil?
        @position.member_id = @member.id
        @position.position = params[:member][:office]
        @position.semester_index = Event.getCurrentSemester

        @member.up_to_date = false
        @member.save

        if @position.save
          redirect_to :controller => :members, :action => :officers
        else
          render :action => "edit"
        end
      else
        flash[:error] = "Member: #{params[:member][:full_name]} not found!"
        render :action => "edit"
      end

    elsif params[:commit] == "Remove"
      remove
    end

  end

  def remove
    @position = Position.find(params[:id])
    @position.destroy
    redirect_to :controller => :members, :action => :officers
  end

  def toggle_complete
    @position = Position.find_by_semester_index_and_member_id(Event.getCurrentSemester, params[:id])
    @position.completed = !@position.completed
    @position.save

    @member = Member.find(params[:id])
    @member.up_to_date = false
    @member.save

    @srcToggle = Toggle.find_by_name("SRC").enabled
    @admin = Member.find_all_by_admin(true)
    if session[:user].office == "President" or session[:user].office == "Internet"
      @officers = Position.find_all_by_position_and_semester_index(0..36, Event.getCurrentSemester);
    end

    redirect_to :controller=> :members, :action => :admin
  end
end
